import {userList} from '../db/testmodel.js';
import url from 'url';

async function dir(ctx,next) {
	// ctx.body = `<h1>首页</h1>`
	// 查询所有用户
const users = await User.findAll();
console.log(users.every(user => user instanceof User)); // true
console.log("All users:", JSON.stringify(users, null, 2));
}

async function getusers(ctx, next) {

	const Urlp = url.parse(ctx.url, true); 		// 拿到页码和每页展示数
	console.log(Urlp);
	
	const page = Urlp.query.page || 1;		// 默认的页码
	const limit = Urlp.query.limit || 5; 	// 默认的每页展示数
	const totalPages = Math.ceil(userList.length / limit);	// 总页码
	const newuserList = [];	// 创建新的数组（用于分页返回对象列表）

	// 判断请求数值是否有效
	if (page <= totalPages && limit <= userList.length) {
		const nowIndex = (page - 1) * limit;		// 起始
		let maxIndex = +nowIndex + +limit;		// 结尾

		if (maxIndex > userList.length) {		// 确保结尾索引不会超过 userList 的长度
			maxIndex = userList.length;
		}

		for (let i = nowIndex; i < maxIndex; i++) {		// 返回分页的内容
			newuserList.push(userList[i]);
		}
		
	} else {
		for (let i = 0; i < 5; i++) {		// 默认展示1-5条
			newuserList.push(userList[i]);
		}

		ctx.redirect(`/userList?page=1&limit=5`);		// 重定向
	}

	ctx.render("userList.html", { userList: newuserList });	//用户信息渲染 

}

async function userById(ctx, next) {
	const id = ctx.params.id;
	User.delete()
}

async function insertuser(ctx, next) {
	ctx.render("adAndUp.html");
}

async function updateuser(ctx, next) {
	ctx.render("adAndUp.html");
}

async function deleteuser(ctx, next) {
	ctx.render("delete.html");
}


export const object = {
	"get@/":dir,
	"get@/users": getusers,
	"get@/users/:id": userById,
	"post@/usersAdd": insertuser,
	"put@/usersUpdate/:id": updateuser,
	"delete@/usersDelete/:id": deleteuser,
};